package com.cskaoyan.realm;

import com.alibaba.druid.util.StringUtils;
import com.cskaoyan.bean.admin.system.ChildBean;
import com.cskaoyan.bean.admin.system.ChildrenBeanX;
import com.cskaoyan.bean.admin.system.SystemPermissionsBean;
import com.cskaoyan.bean.pojo.Admin;
import com.cskaoyan.bean.pojo.AdminExample;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.RoleMapper;
import com.cskaoyan.mapper.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//先认证后授权
@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserMapper userMapper;

//    @Autowired
//    WebApplicationContext webApplicationContext;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //提供认证信息 👉 credentials
        //系统中保存的用户名和对应的credentials和上面的一些信息一致
//        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        MallToken token = ((MallToken) authenticationToken);
        String type = token.getType();


        String username = token.getUsername();
        AuthenticationInfo info = dealInfoByType(type,username);

//        setSuperAdminPermissionsIntoContext();

        //第一个参数Principal：就是主角信息，在后面授权的时候可以获得这个值，Session中的principal信息
        //                   你传入一个什么样的principal信息，认证成功之后就能够获得什么样的principal
        //第二个参数credentials：会和token中的password做比对
        return info;
    }

    private void setSuperAdminPermissionsIntoContext() {
        //初始化*的权限
        List<SystemPermissionsBean> systemPermissions = roleMapper.selectAllSystemPermissons();

        List<String> assignedPermissions = new ArrayList<>();
        for (SystemPermissionsBean systemPermission : systemPermissions) {
            List<ChildrenBeanX> childrenXs = systemPermission.getChildren();
            for (ChildrenBeanX childrenX : childrenXs) {
                List<ChildBean> childrens = childrenX.getChildren();
                for (ChildBean children : childrens) {
                    assignedPermissions.add(children.getId());
                }
            }
        }

//        ServletContext servletContext = webApplicationContext.getServletContext();
//        servletContext.setAttribute("*",assignedPermissions);
    }

    private AuthenticationInfo dealInfoByType(String type,String username) {
        String credentials = null;
        if("admin".equals(type)){
            credentials = adminMapper.selectPasswordByUsername(username);
        }else if("wx".equals(type)){
            credentials = userMapper.selectPasswordByUsername(username);
        }
        return new SimpleAuthenticationInfo(username,credentials,this.getName());
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权 → 提供权限
        //获得principal信息
        //获得doGetAuthen方法（上面这个方法），构造的authenticationInfo中的principal信息
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();

        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        if(!StringUtils.isEmpty(primaryPrincipal)){
            criteria.andUsernameEqualTo(primaryPrincipal);
        }
        criteria.andDeletedEqualTo(false);

        List<Admin> admins = adminMapper.selectByExample(adminExample);
        Integer[] roleIds = admins.get(0).getRoleIds();

        List<String> permissions = adminMapper.selectPermissionsByPrincipal(roleIds);

//        if(permissions.contains("*")){
//            ServletContext servletContext = webApplicationContext.getServletContext();
//            permissions = (List<String>) servletContext.getAttribute("*");
//        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);//提供权限 👉 找到所有的钥匙

        return authorizationInfo;
    }
}
